<?php
namespace App\Controllers;

/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 *
 * @package CodeIgniter
 */

use App\Controllers\BaseController;
use App\Models\AdminModel;
use App\Models\RbacModel;

class AdminBase extends BaseController
{

    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    // protected $helpers = [];

    public $adminid;
    public $admin;
    public $mod;

    protected $adminModel;
    protected $rbacModel;

    /**
     * Constructor.
     */
    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);

        if (!defined('IS_ADMIN') || !IS_ADMIN) {
            $this->goTo404();
            exit();
        }

        $this->adminModel = new AdminModel();
        $this->rbacModel = new RbacModel();

        //登录判断
        $this->admin = $this->is_admin_login();

        if ((!$this->adminid || !$this->admin) && (!isset($this->uri[1]) || (isset($this->uri[1]) && $this->uri[1] != 'login'))) {
            $this->adminMsg(-1, '请登录', ['url' => url('admin/login/index', ['backurl' => AMS_NOW_URL])]);
        }

        // 权限判断
        if (($this->uri[0] == 'admin' && (isset($this->uri[1]) && $this->uri[1] != 'login') && !$this->is_auth($this->uri)) && $this->adminid != 1) {
            (IS_AJAX ? exit('您无权限操作:'.$uri) : $this->adminMsg(1, '您无权限操作', ['url' => $this->uri]));
        }

        $this->renderer->setData(['admin' => $this->admin]);
    }

    //是否登陆
    protected function is_admin_login()
    {
        if (IS_ADMIN && isset($this->uri[1]) && $this->uri[1] == 'login') {
            return false;
        }

        $adminid = $this->adminModel->get_adminid();
        $this->admin = $this->session->get('admin');
        $this->adminid = $this->session->get('adminid');
        if ($this->adminid == false || $adminid != $this->adminid) {
            return false;
        }

        $rt = $this->adminModel->get_admin($this->adminid);
        if ($rt['code'] != 0) {
            $this->admin = false;
            return false;
        }

        $this->admin = $rt['data'];
        return $this->admin;
    }

    //提示消息
    public function adminMsg($code, $msg, $data = [])
    {
        $backurl = ''; //跳转的地址
        $time = isset($data['time']) ? intval($data['time']) : 0; //默认3秒跳转

        if (isset($data['url']) && $data['url']) {
            $backurl = $this->xss_clean($data['url']);
            if (strpos($backurl, '?backurl=') !== false) {
                $arr = explode('?backurl=', $backurl);
                if (isset($arr[1]) && $arr[1]) {
                    $backurl = $arr[0] . '?backurl=' . urlencode($arr[1]);
                }
            }
        } else if (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'php?') !== false) {
            $backurl = $this->xss_clean($_SERVER['HTTP_REFERER']);
        } else if (!$backurl) {
            $backurl = SELF;
        }

        if ($this->request->getGet('is_ajax') || IS_AJAX || $this->request->isAJAX()) {
            exit($this->_json($code, $msg));
        }

        $vdata = [
            'code' => $code,
            'msg' => $msg,
            'url' => $backurl,
            'time' => $time,
            'mark' => $code,
        ];
        echo view('msg.html', $vdata);
        exit();
    }

    protected function is_auth($uri = '')
    {
        if (!$uri || $this->admin['roleid'] == 1) {
            return true;
        }
        if (is_array($uri)) {
            $uri = implode('/', $uri);
        }

        //忽略验证
        $skip = [
            'admin/home/index',
            'admin/home/main',
        ];

        $auth = $this->rbacModel->getRoleAuth($this->admin);
        if (!in_array($uri, $auth)) {
            $this->adminMsg(1, '您还没有权限(' . $uri . ')');
        }
        return true;
    }

    /**
     * 后台日志
     */
    protected function addSystemLog($action, $admin = [])
    {
        $ip = $this->request->getIPAddress();

        if (!$this->admin || !$this->admin['uid']) {
            $logarr = ['action' => $action, 'ip' => $ip, 'uid' => 0, 'username' => $admin['username']];
        } else {
            $logarr = ['action' => $action, 'ip' => $ip, 'uid' => $this->admin['uid'], 'username' => $this->admin['username']];
        }
        $this->systemModel->insterLog($logarr);
    }

    protected function getMod()
    {
        $mod = $this->request->getGet('mod');
        ams_clean_xss($mod);
        $this->mod = $mod;
        return $mod;
    }

}
